<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.ruleName"
        placeholder="规则名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="success"
        icon="el-icon-add"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="编号" prop="id" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规则名称" class-name="status-col" min-width="120">
        <template slot-scope="{ row }">
          {{ row.ruleName }}
        </template>
      </el-table-column>
      <el-table-column label="渠道" min-width="120" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.channelId === 0">全部渠道</span>
          <span v-else>{{ row.channelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预设规则" min-width="240" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.ruleId === 1">10分钟无新增注册数</span>
          <span v-if="row.ruleId === 2">注册数环比昨天同一时段下降超20%</span>
          <span v-if="row.ruleId === 3">完件率同比上一小时下降超10%</span>
        </template>
      </el-table-column>
      <el-table-column label="创建更新时间" min-width="180" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.uptDateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="监控时段" min-width="120" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.timePeriods }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="重复报警间隔时间" min-width="200" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timeInterval }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="累计报警次数" min-width="200" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sysValue }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" min-width="120" align="center">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.ruleStatus"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            style="width:100%;margin-top:10px"
            @change="changePageSwitch(row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="报警状态" min-width="120" align="center">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.warningStatus"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            style="width:100%;margin-top:10px"
            @change="changePageSwitch(row)"
          />
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        width="140"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="ruleList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="sysDict"
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="规则名称">
          <el-input v-model="sysDict.ruleName" />
        </el-form-item>
        <el-form-item label="监控时段">
          <el-input v-model="sysDict.timePeriods" placeholder="6-18" />
        </el-form-item>
        <!-- <el-form-item label="重复报警间隔时间(秒)">
          <el-input v-model="sysDict.timeInterval" type="number" />
        </el-form-item> -->

        <el-form-item label="预设规则">
          <el-select
            v-model="sysDict.ruleId"
            placeholder="预设规则"
            style="width: 250px;"
            class="filter-item"
          >
            <el-option label="10分钟无新增注册数" :value="1" />
            <el-option label="注册数环比昨天同一时段下降超20%" :value="2" />
            <el-option label="完件率同比上一小时下降超10%" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择渠道">
          <el-select
            v-model="sysDict.channelId"
            filterable
            :filter-method="dataFilter"
            placeholder="选择渠道"
            style="width: 250px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          >
            <el-option
              v-for="item in options"
              :key="item.channelId"
              :label="item.channel_name"
              :value="item.channelId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? insertRule() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChannelIdAndNick } from '@/api/user';
import { ruleList, updateRule, insertRule } from '@/api/sys';
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
export default {
  name: 'Sysdict',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        sysLabel: ''
      },
      sysDict: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        username: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      optionsCopy: [],
      options: [],
      listLoading: false
    };
  },
  created() {
    this.ruleList(this.listQuery);
  },
  methods: {
    dataFilter(val) {
      this.value = val;
      if (val) {
        // val存在
        this.options = this.optionsCopy.filter(item => {
          if (
            !!~item.channel_name.indexOf(val) ||
            !!~item.channel_name.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        // val为空时，还原数组
        this.options = this.optionsCopy;
      }
    },
    async getChannelIdAndNick() {
      const res = await getChannelIdAndNick(this.listQuery);
      this.optionsCopy[0] = { channel_name: '全部', channelId: 0 };
      this.options[0] = { channel_name: '全部', channelId: 0 };
      res.data.data.forEach(element => {
        if (element.channel_name !== null) {
          this.optionsCopy.push(element);
          this.options.push(element);
        }
      });
    },
    // 获取用户列表
    async ruleList() {
      const res = await ruleList(this.listQuery, this.listQuery.sysLabel);
      try {
        res.data.data.records.forEach(ele => {
          if (ele.ruleStatus === 0) {
            ele.ruleStatus = false;
          } else if (ele.ruleStatus === 1) {
            ele.ruleStatus = true;
          }
          if (ele.warningStatus === 0) {
            ele.warningStatus = false;
          } else if (ele.warningStatus === 1) {
            ele.warningStatus = true;
          }
        });
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
      } catch (error) {
        console.log(error);
      }
    },
    changePageSwitch(row) {
      // 贷款详情页开关0-关，1-开
      if (row.ruleStatus) {
        row.ruleStatus = 1;
      } else {
        row.ruleStatus = 0;
      }
      if (row.warningStatus) {
        row.warningStatus = 1;
      } else {
        row.warningStatus = 0;
      }
      updateRule(row).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: 'Success',
            message: '更新成功',
            type: 'success',
            duration: 2000
          });
          this.ruleList(this.listQuery);
        } else {
          this.$notify({
            title: 'fail',
            message: '更新失败',
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.ruleList();
    },
    cancel() {
      this.dialogFormVisible = false;
      this.ruleList();
    },
    resetTemp() {
      this.sysDict = {};
    },
    handleCreate() {
      this.getChannelIdAndNick();
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    insertRule() {
      insertRule(this.sysDict).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: 'Success',
            message: '新增成功',
            type: 'success',
            duration: 2000
          });
          this.cancel();
        } else {
          this.$notify({
            title: 'fail',
            message: '新增失败',
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
    async handleUpdate(row) {
      this.getChannelIdAndNick();
      this.sysDict = row;
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
    },
    updateData() {
      if (this.sysDict.ruleStatus) {
        this.sysDict.ruleStatus = 1;
      } else {
        this.sysDict.ruleStatus = 0;
      }
      if (this.sysDict.warningStatus) {
        this.sysDict.warningStatus = 1;
      } else {
        this.sysDict.warningStatus = 0;
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateRule(this.sysDict).then(res => {
            if (res.data.code === 200) {
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 2000
              });
              this.cancel();
            } else {
              this.$notify({
                title: 'fail',
                message: '更新失败',
                type: 'fail',
                duration: 2000
              });
            }
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      });
      this.list.splice(index, 1);
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? 'ascending' : 'descending';
    }
  }
};
</script>

<style scoped>
.pic {
  width: 150px;
  margin-top: 10px;
  margin-left: 10px;
}
.ok {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(35, 248, 124);
}
.fail {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(240, 174, 76);
}
.info {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
}
.info-name {
  margin-left: 50px;
  margin-top: 10px;
  color: rgb(172, 176, 177);
}
.title {
  margin-top: 10px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 400;
}
.box {
  margin-top: 10px;
  width: 100%;
  border: solid rgb(138, 219, 230) 2px;
}
.nick {
  font-size: 30px;
  font-weight: 600;
}
.link-top {
  margin-left: 10px;
  margin-top: 10px;
  width: 100%;
  height: 2px;
  border-top: solid rgb(138, 219, 230) 2px;
}
.link-title {
  margin-left: 10px;
  margin-top: 10px;
  width: 80px;
  height: 2px;
  border-top: solid rgb(172, 176, 177) 2px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
